package java;

import java.util.ArrayList;
import java.util.List;

public class Question39 {
    public static void main(String[] args) {
        int[] candidates = {2,3,6,7};
        List<List<Integer>> res = combinationSum(candidates,7);
        for (List<Integer> item: res){
            for (Integer integer : item) {
                System.out.print(integer);
            }
            System.out.println();
        }
    }
    public static List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        if (candidates == null || candidates.length < 1 || target < 1){
            return res;
        }
        List<Integer> oneRes = new ArrayList<>();
        int sum = 0;
        combinationSumDiGui(res,oneRes,sum,candidates,target);
        return res;
    }

    private static void combinationSumDiGui(List<List<Integer>> res, List<Integer> oneRes, int sum, int[] candidates, int target) {
        if (sum > target){
            return;
        }
        if (sum == target){
            List<Integer> oneResTemp = new ArrayList<>(oneRes);
            res.add(oneResTemp);
            return;
        }
        for (int i = 0;i < candidates.length; i ++){
            if (!oneRes.isEmpty() && oneRes.get(oneRes.size() - 1) > candidates[i]){
                continue;
            }
            sum += candidates[i];
            oneRes.add(candidates[i]);
            combinationSumDiGui(res,oneRes,sum,candidates,target);
            oneRes.remove(oneRes.size() - 1);
            sum -= candidates[i];
        }
    }
}
